package cn.com.thinvent.dispatch.service.biz.impl;

import cn.com.thinvent.dispatch.dao.ModelTargetMapper;
import cn.com.thinvent.dispatch.dao.ModelTaskTargetMappingMapper;
import cn.com.thinvent.dispatch.entity.ModelTarget;
import cn.com.thinvent.dispatch.entity.ModelTaskTargetMapping;
import cn.com.thinvent.dispatch.entity.response.PagedGridResult;
import cn.com.thinvent.dispatch.service.biz.ModelTargetService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
public class ModelTargetServiceImpl implements ModelTargetService {

    @Resource
    private ModelTargetMapper modelTargetMapper;
    @Resource
    private ModelTaskTargetMappingMapper modelTaskTargetMappingMapper;


    @Override
    public PagedGridResult<ModelTarget> list(String name,String tag, Integer pageNum, Integer pageSize) {
        PagedGridResult<ModelTarget> pagedGridResult = new PagedGridResult<>();
        Integer pageBegin = (pageNum - 1) * pageSize;
        List<ModelTarget> list = modelTargetMapper.list(name,tag,pageBegin, pageSize);
        Long count = modelTargetMapper.count(name);
        pagedGridResult.setRows(list);
        pagedGridResult.setRecords(count);
        pagedGridResult.setTotal((Integer.parseInt(count.toString()) + pageSize - 1 )/ pageSize);
        pagedGridResult.setPage(pageNum);
        return pagedGridResult;
    }

    @Override
    public ModelTarget saveOrUpdate(ModelTarget modelTarget) {
        Date date = new Date();
        if(modelTarget.getId() == null) {
            modelTarget.setCreateTime(date);
            modelTarget.setUpdateTime(date);
            modelTargetMapper.insert(modelTarget);
        } else {
            modelTarget.setUpdateTime(date);
            modelTargetMapper.update(modelTarget);
        }
        return modelTarget;
    }

    @Override
    public Integer delete(Integer id) {
        List<ModelTaskTargetMapping> modelTaskTargetMapping = modelTaskTargetMappingMapper.getListByTargetId(id);
        if(modelTaskTargetMapping.isEmpty()){
            return modelTargetMapper.deleteById(id);
        }else{
            return 0;
        }

    }
}
